import 'package:flutter/foundation.dart';
import '../database/database_helper.dart';
import '../models/diary.dart';
import '../utils/date_util.dart';

class DiaryProvider with ChangeNotifier {
  final DatabaseHelper _dbHelper = DatabaseHelper();
  Diary? _currentDiary;
  List<Diary> _diaryHistory = [];
  List<MoodTag> _allTags = [];
  bool _isLoading = false;

  // 获取当前日记
  Diary? get currentDiary => _currentDiary;
  
  // 获取日记历史
  List<Diary> get diaryHistory => _diaryHistory;
  
  // 获取所有标签
  List<MoodTag> get allTags => _allTags;
  
  // 加载状态
  bool get isLoading => _isLoading;

  // 初始化，加载今天的日记和所有标签
  Future<void> init() async {
    await Future.wait([
      loadTodayDiary(),
      loadAllTags(),
    ]);
  }

  // 加载今天的日记
  Future<void> loadTodayDiary() async {
    _isLoading = true;
    notifyListeners();

    try {
      final today = DateUtil.getCurrentDate();
      final diaryMap = await _dbHelper.getDiaryByDate(today);
      
      if (diaryMap != null) {
        final diaryId = diaryMap['id'] as int;
        final tags = await _loadTagsForDiary(diaryId);
        _currentDiary = Diary.fromMap(diaryMap, tags: tags);
      } else {
        _currentDiary = null;
      }
    } catch (e) {
      debugPrint('加载今日日记失败: $e');
      _currentDiary = null;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 加载所有情绪标签
  Future<void> loadAllTags() async {
    try {
      final tagMaps = await _dbHelper.getMoodTags();
      _allTags = tagMaps.map((map) => MoodTag.fromMap(map)).toList();
    } catch (e) {
      debugPrint('加载情绪标签失败: $e');
      _allTags = [];
    }
    notifyListeners();
  }

  // 加载特定类别的情绪标签
  Future<List<MoodTag>> loadTagsByCategory(String category) async {
    try {
      final tagMaps = await _dbHelper.getMoodTagsByCategory(category);
      return tagMaps.map((map) => MoodTag.fromMap(map)).toList();
    } catch (e) {
      debugPrint('加载情绪标签失败: $e');
      return [];
    }
  }

  // 加载日记的标签
  Future<List<MoodTag>> _loadTagsForDiary(int diaryId) async {
    try {
      final tagMaps = await _dbHelper.getTagsForDiary(diaryId);
      return tagMaps.map((map) => MoodTag.fromMap(map)).toList();
    } catch (e) {
      debugPrint('加载日记标签失败: $e');
      return [];
    }
  }

  // 保存日记
  Future<bool> saveDiary(String content, List<int> tagIds, {int? moodId}) async {
    _isLoading = true;
    notifyListeners();

    try {
      final now = DateTime.now();
      final today = DateUtil.formatDate(now);
      final currentTime = DateUtil.formatDateTime(now);
      
      // 检查今天是否已有日记
      final existingDiary = await _dbHelper.getDiaryByDate(today);
      
      final diary = Diary(
        id: existingDiary?['id'] as int?,
        date: today,
        content: content,
        moodId: moodId,
        createdAt: currentTime,
      );
      
      int diaryId;
      if (existingDiary != null) {
        // 更新现有日记
        await _dbHelper.database.then((db) => 
          db.update(
            'diaries', 
            diary.toMap(),
            where: 'id = ?',
            whereArgs: [existingDiary['id']],
          )
        );
        diaryId = existingDiary['id'] as int;
        
        // 删除旧的标签关联
        await _dbHelper.database.then((db) => 
          db.delete(
            'diary_tags',
            where: 'diary_id = ?',
            whereArgs: [diaryId],
          )
        );
      } else {
        // 插入新日记
        diaryId = await _dbHelper.insertDiary(diary.toMap());
      }
      
      // 关联标签
      if (tagIds.isNotEmpty) {
        await _dbHelper.linkDiaryWithTags(diaryId, tagIds);
      }
      
      // 加载新的标签
      final tags = await _loadTagsForDiary(diaryId);
      _currentDiary = diary.copyWith(id: diaryId, tags: tags);
      
      // 刷新日记历史
      await loadDiaryHistory();
      
      return true;
    } catch (e) {
      debugPrint('保存日记失败: $e');
      return false;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 加载日记历史
  Future<void> loadDiaryHistory() async {
    _isLoading = true;
    notifyListeners();

    try {
      final diaryMaps = await _dbHelper.getAllDiaries();
      _diaryHistory = [];
      
      for (var diaryMap in diaryMaps) {
        final diaryId = diaryMap['id'] as int;
        final tags = await _loadTagsForDiary(diaryId);
        _diaryHistory.add(Diary.fromMap(diaryMap, tags: tags));
      }
    } catch (e) {
      debugPrint('加载日记历史失败: $e');
      _diaryHistory = [];
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 获取特定日期的日记
  Future<Diary?> getDiaryByDate(String date) async {
    try {
      final diaryMap = await _dbHelper.getDiaryByDate(date);
      
      if (diaryMap != null) {
        final diaryId = diaryMap['id'] as int;
        final tags = await _loadTagsForDiary(diaryId);
        return Diary.fromMap(diaryMap, tags: tags);
      }
      
      return null;
    } catch (e) {
      debugPrint('获取日记失败: $e');
      return null;
    }
  }
} 